
import { _decorator, Component, EventTouch, Node, Animation, UITransform, Vec2, Vec3, ProgressBar, Label, Sprite, Size } from 'cc';
import { MonsterManager } from './monster/MonsterManager';
import { FightControl, GameModel, GameState } from './FightControl';
import { MainGun } from './gun/MainGun';
import { bulletManger } from './bullet/BulletManager';
import { SecondaryGuns } from './gun/SecondaryGuns';
import { SkillManager } from './skill/SkillManager';
import EvtManger from '../tools/EvtManger';
import { AppControll, ConfigKey, EventName, PopView } from '../manager/AppControll';
import { GameData } from '../system/GameData';
import { DataHelper } from '../system/DataHelper';
import { Loader } from '../tools/LoadManger';
import { SoundManager } from '../manager/SoundManger';
import { ChangeRefresh } from './ChangeRefresh';
import { LevelChallenge } from '../pop/LevelChallenge';
import { levelModel } from './levelModel/levelModel';
import { Tools } from '../tools/Tools';
import { PopManager } from '../manager/PopManager';
import { SystemMessage } from '../pop/SystemMessage';
const { ccclass, property } = _decorator;

@ccclass('FightView')
export class FightView extends Component {
    private mTouchLayer: Node = null;
    private mMonster: Node = null;
    private mMainGun: MainGun = null;
    private mBullet: Node = null;
    private mGameState = GameState.default;
    private mMonsterManger: MonsterManager = null;
    private mNdSecondaryGuns: SecondaryGuns = null;
    private mSkill: Node = null;
    private mTime: number = 0;  
    private mCurTime: number = 0;
    private mBossTimer: number = 0;
    private mNdGift: Node = null;
    private mNdBoss: Node = null;
    private mBIsFirstBoss = true;
    private mBIsFirstGift = true;
    private mNBossCountDown = null;
    private mNdBg: Node = null;
    private mBIsBossAppears: boolean = false;
    private mBIsGiftAppears: boolean = false;
    private mNdChange: Node = null;
    private mLevelModel: levelModel = null;

    protected onLoad(): void {
        this.mTouchLayer = this.node.getChildByName("touchLayer");
        this.mMonster = this.node.getChildByName("monsterPoint");
        this.mSkill = this.node.getChildByName("skillPoint");
        this.mBullet = this.node.getChildByName("bulletPoint");
        this.mMainGun = this.node.getChildByName("mainGun").getComponent(MainGun);
        //this.mNdSecondaryGuns = this.node.getChildByName("secondGuns").getComponent(SecondaryGuns);
        this.mMonsterManger = new MonsterManager(this.mMonster);
        this.mNdGift = this.node.parent.getChildByName("gift");
        this.mNdBoss = this.node.parent.getChildByName("bossComing");
        this.mNdChange = this.node.parent.getChildByName("stagetChange");
        this.mNdBg = this.node.getChildByName("bg");
        this.mLevelModel = this.node.parent.getComponent(levelModel);
        SkillManager.Instance<SkillManager>().InitSkillManager(this.mSkill);
        bulletManger.InitBulletManager(this.mBullet);
        this.RegisteredEvent();
        this.mNdGift.getComponent(Animation).on(Animation.EventType.FINISHED, () => {
            this.mTime = 0;
            this.mBIsGiftAppears = false;
            this.mNdGift.active = false;
        })
        FightControl.gameState = GameState.start;
        GameData.bossTime = Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.bossRefreshRegular).value);
        GameData.giftTime = Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.giftRefreshRegular).value);
        this.ChangeRefresh();
        AppControll.Platform.SendBuryPoint(100000);
        AppControll.Platform.ReoprtScene(7);
        this.ShowSign();
    }

    ShowSign() {
        if (GameData.playerData.signInCount < 2 && GameData.playerData.Honor >= Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.sevenSign).value)) {
            GameData.playerData.singnGuide = false;
            PopManager.Instance<PopManager>().ShowPop(PopView.sevenSignIn);
        }
    }

    RegisteredEvent() {
        EvtManger.on(EventName.showGift, this, this.ShowGift);
        EvtManger.on(EventName.hideGift, this, this.HideGift);
        EvtManger.on(EventName.showBossHp, this, this.ShowBossHp);
        EvtManger.on(EventName.bossDeath, this, this.BossDeath);
        EvtManger.on(EventName.monsterRefreshChange, this, this.ChangeRefresh);
        EvtManger.on(EventName.levelChallenge, this, this.LevelModel);
        EvtManger.on(EventName.normalChanllenge, this, this.normalModel);
        this.mTouchLayer.on(Node.EventType.TOUCH_START, this.OnTouchStart, this);
        this.mTouchLayer.on(Node.EventType.TOUCH_MOVE, this.OnTouchMove, this);
        this.mTouchLayer.on(Node.EventType.TOUCH_END, this.OnTouchEnd, this);
        this.mTouchLayer.on(Node.EventType.TOUCH_CANCEL, this.OnTouchCancel, this);
    }

    HideGift() {
        this.mTime = 0;
        this.mBIsGiftAppears = false;
    }

    LevelModel() {
        FightControl.gamemodel = GameModel.levelModel;
        this.mNdChange.active = false;
        this.mMonsterManger.ChangeLevelMode();
        this.mLevelModel.StartLevelMode();
        this.ShowGift();
        this.BossDeath();
    }

    normalModel() {
        GameData.isPause = false;
        FightControl.gamemodel = GameModel.normal;
        this.mNdChange.active = true;
        let refConfig = DataHelper.GetMonsterRefreshConfig();
        Loader.LoadBg(GameData.backgroundPath + refConfig.bgImage, (spf) => {
            this.mNdBg.getComponent(Sprite).spriteFrame = spf;
        });
        if (GameData.playerData.challengeCount + GameData.playerData.adChallengeCount > 0) {
            PopManager.Instance<PopManager>().ShowPop(PopView.levelChallenge)
        }
    }

    //切换阶段
    ChangeRefresh() {
        let refConfig = DataHelper.GetMonsterRefreshConfig();
        Loader.LoadBg(GameData.backgroundPath + refConfig.bgImage, (spf) => {
            this.mNdBg.getComponent(Sprite).spriteFrame = spf;
        });
        
        this.mNdBg.getComponent(UITransform).contentSize = new Size(refConfig.bgSize[0], refConfig.bgSize[1]);
        this.mNdChange.getComponent(ChangeRefresh).InitRefreshChange(refConfig);
    }

    ShowBossHp(hp: number) {
        this.mNdBoss.getChildByName("bossHp").getComponent(ProgressBar).progress = hp;
    }

    BossDeath() {
        this.mNdBoss.getComponent(Animation).stop();
        this.mNdBoss.children.forEach(node => {
            node.active = false;
        })
        this.mBossTimer = 0;
        this.mNBossCountDown = null;
        this.mBIsBossAppears = false;
    }

    protected onDestroy(): void {
        EvtManger.off(EventName.showGift, this, this.ShowGift);
    }

    ShowGift() {
        if (!GameData.playerData.giftGuide) {
            this.mNdGift.getChildByName("firseClick").active = false;
        }
        this.mTime = 0;
        this.mNdGift.getComponent(Animation).stop();
        this.mBIsGiftAppears = false;
        this.mNdGift.active = false;
    }

    OnTouchStart() {

    }

    OnTouchMove() {

    }

    OnTouchEnd(touch: EventTouch) {
        let point = this.node.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(touch.getUILocation().x, touch.getUILocation().y, 0));
        MonsterManager.ltMonster.sort((a, b) => { return b.getSiblingIndex() - a.getSiblingIndex() });
        let lt = Tools.GetLtMonster();
        for (let index = 0; index < lt.length; index++) {
            const element = lt[index];
            if (element.getComponent(UITransform).getBoundingBox().contains(new Vec2(point.x, point.y))) {
                EvtManger.do(EventName.lockMonsterByTouch, element);
                break;
            }
        }
        AppControll.ShelvedTime = 0;
        EvtManger.do(EventName.shootByTouch);
    }

    OnTouchCancel() {

    }

    start() {
        this.mGameState = GameState.start;
    }

    protected update(dt: number): void {
        if (FightControl.gamemodel == GameModel.levelModel) return;

        if (GameData.playerData.upgradeTotal && GameData.playerData.upgradeTime) {
            if (GameData.playerData.upgradeTotal * 1000 - (Date.now() - GameData.playerData.upgradeTime) <= 0) {
                PopManager.Instance<PopManager>().ShowPop(PopView.systemMessage, nd => {
                    nd.getComponent(SystemMessage).InitContent("副炮概率升级完成！");
                })
                
                GameData.playerData.upgradeTotal = null;
                GameData.playerData.upgradeTime = null
                GameData.playerData.randomLevel += 1;
            };
        }

        if (GameData.isPause) return;

        if (this.mGameState == GameState.start) {
            AppControll.ShelvedTime += dt;
            this.mTime += dt;
            this.mBossTimer += dt;
            if (AppControll.ShelvedTime >= Number.parseFloat(DataHelper.GetConfigByKey(ConfigKey.chapingShow).value) && AppControll.IsShowInitInterstitial == false) {
                AppControll.IsShowInitInterstitial = true;
                AppControll.ShelvedTime = 0;
            }
            
            if (this.mTime >= GameData.giftTime && this.mNdGift.active == false && this.mBIsGiftAppears == false) {
                this.mBIsGiftAppears = true;
                if (GameData.playerData.giftGuide) {
                    GameData.playerData.giftGuide = false;
                    this.mNdGift.getChildByName("firseClick").active = true;
                } else {
                    this.mNdGift.getChildByName("firseClick").active = false;
                }
                if (this.mBIsFirstGift) {
                    this.mNdGift.active = true;
                    this.mNdGift.getComponent(Animation).play();
                    this.mBIsFirstGift = false;
                    GameData.giftTime = Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.giftRefreshRandom).value);
                    return;
                }
                if (Math.random() <= Number.parseFloat(DataHelper.GetConfigByKey(ConfigKey.giftRefreshChance).value)) {
                    this.mNdGift.active = true;
                    GameData.playerData.giftGuide = false;
                    this.mNdGift.getChildByName("firseClick").active = false;
                    this.mNdGift.getComponent(Animation).play();
                } else {
                    this.mBIsGiftAppears = false;
                }
            }
            if (this.mBossTimer >= GameData.bossTime && MonsterManager.ndBoss == null && this.mBIsBossAppears == false) {
                this.mBIsBossAppears = true;
                this.mNBossCountDown += dt
                if (this.mBIsFirstBoss) {
                    SoundManager.Instance<SoundManager>().PlayEffect("ui/bossComing");
                    this.mNdBoss.getComponent(Animation).play();
                    this.mNdBoss.getChildByName("bossHp").getComponent(ProgressBar).progress = 1;
                    this.mMonsterManger.CreateBoss();
                    this.mBIsFirstBoss = false;
                    GameData.bossTime = Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.bossRefreshRandom).value);
                    return;
                }
                if (Math.random() <= Number.parseFloat(DataHelper.GetConfigByKey(ConfigKey.bossRefreshChance).value)) {//N
                    SoundManager.Instance<SoundManager>().PlayEffect("ui/bossComing");
                    this.mNdBoss.getComponent(Animation).play();
                    this.mNdBoss.getChildByName("bossHp").getComponent(ProgressBar).progress = 1;
                    this.mMonsterManger.CreateBoss();
                }
            }
            if (MonsterManager.ndBoss != null) {
                this.mNBossCountDown += dt
                let contDown = Number.parseInt(DataHelper.GetConfigByKey(ConfigKey.bossStopTime).value) - this.mNBossCountDown;
                if (contDown <= 0) { contDown = 0 };
                this.mNdBoss.getChildByName("bossHp").getChildByName("countDown").getComponent(Label).string = Math.floor(contDown) + "";
            }
            if (this.mMonsterManger) {
                this.mMonsterManger.Tick(dt);
            }
            if (this.mMainGun) {
                this.mMainGun.Tick(dt)
            }
            if (this.mNdSecondaryGuns) {
                this.mNdSecondaryGuns.Tick(dt);
            }
        }
    }

    protected lateUpdate(dt: number): void {
        this.mCurTime++;
        if (this.mCurTime % 20 == 0) {
            GameData.UpdateData();
        }
    }
}
